<?php


namespace app\common\cachemodel\privatearea;


use app\common\lib\Aes;
use app\common\model\BaseCache;
use think\Db;
use think\Log;
use Exception;
use XznsTools\cache\CacheManage;

class PrivateAreaAstro extends BaseCache
{
    protected $table = 'wechat_backup_07_18_14_43_00.private_area_astro';

    protected $cacheModel = 'privatearea.astro';

    /**
     * 更新私域H5 占星师信息
     * @param $astroId
     * @param $map
     * @return int|string
     */
    public function SavaData($astroId, $map)
    {
        try
        {
            $this->where(['id' => $astroId])->update($map);

            CacheManage::getInstance()->setCacheConfig($this->cacheModel, $astroId)->rmCache();
            return true;
        }
        catch (Exception $e)
        {
            Log::write('私域H5 PrivateAreaAstro model 异常：' . $e->getMessage() . '失败行数：' . $e->getLine(), 'error');
            return false;
        }
    }

    /**
     * 缓存获取私域H5 占星师信息
     * @param int $astroId 用户ID
     * @param array $filed
     * @return array|mixed
     * @throws Exception
     */
    public function getPrivateAreaInfo(int $astroId, array $filed = [])
    {
        $data = CacheManage::getInstance()->setCacheConfig($this->cacheModel, $astroId)->getDataAndSet(function () use ($astroId)
        {
            return $this->getPrivateAreaInfoFromDms($astroId);
        }, $filed);

        return $data ? arrayKeyData2int($data, ['id', 'status', 'token_expire',]) : [];
    }

    /**
     * 数据库获取私域H5 占星师信息
     * @param int $astroId
     * @return array|mixed
     */
    private function getPrivateAreaInfoFromDms(int $astroId)
    {
        try
        {
            $data = $this->where(['id' => $astroId])->field('id,status,telphone,name,token,token_expire')->findOrFail()->toArray();
        }
        catch (Exception $e)
        {
            $data = [];
        }

        return $data;
    }

    /**
     * 获取 私域占星师 相关联的 准了占星师ID 【身份证号相等】
     * @param int $id
     * @return int
     */
    public function getZhunleAstrIdById(int $id)
    {
        $data = Db::table('wechat_backup_07_18_14_43_00.private_area_astro')->alias('pa')
            ->join('wechat_backup_07_18_14_43_00.zlcr_astr_info i', 'pa.id_card=i.id_card')
            ->join('wechat_backup_07_18_14_43_00.zlcr_astr a', 'i.astr_id=a.id')
            ->where(['pa.id' => $id, 'a.check_status' => 40])->field('i.astr_id')->find();

        if ($data)
        {
            return (int)$data['astr_id'];
        } else
        {
            return 0;
        }
    }
}
